<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | 首页控制器（H5）
// +----------------------------------------------------------------------
// | Author: july <1499801239@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
class Index extends Controller
{
   	private function base(){
 		$session = Session::get('name');
	    if(!$session){
	        $this->redirect('Index/errors');
	    }        
    }
    public function errors(){
       return $this->fetch();
    }
	
	// 首页  未登录、未认证完整 显示最高；认证完成默认额度。
    public function index() {
        $count=$dateY=$dateM=$dateD=$endDay=$yuDay=$isShow=0;
        $session = Session::get('name');
        $this->assign('session',$session?$session:'null');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID']; 
        //未登录
        $goodsLits = Db::table('xb_goods')->field('ID,SalePrice,jiekuandays')->where('IsShelves',1)->select();//上架产品
        for($i=0;$i<count($goodsLits);$i++){
            $moneyArr[]=$goodsLits[$i]['SalePrice'];
            $timeArr[]=$goodsLits[$i]['jiekuandays'];
        }
        $goodsLits?$this->assign(['moneyArr'=>$moneyArr,'timeArr'=>$timeArr]):$this->assign(['moneyArr'=>[],'timeArr'=>[]]);
        $applyData=null;
        $bankData=null;
        $default = Db::table('xb_sys_basicinfo')->select();
        if(count($default)!=1) exit('最大额度设置有误');
        //登录
        if($session!=null){
            $result = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank')->where('UserName',$session)->find();
            if($result){ foreach($result as $val){if($val==1){$count ++;}}} //已认证项
            $mustAuthen = Db::table('xb_renzen_parameter')->where('IsMust',1)->select();//必须认证项
            if(!$mustAuthen) exit('必须认证项设置有误');
            if($count!= count($mustAuthen))
            {
                $count = count($mustAuthen)-$count;
            }else{ //认证完整
                $count=0;
                $defaults = Db::table('xb_mem_info')->where('UserName',$session)->value('LimitBalcance');
                $default[0]['weimoney']=$defaults;
                if(count($defaults)!=1) exit('默认额度设置有误');
            }
            
            $applyData = Db::table('xb_loans_applylist a')->field('a.ForbidDay,a.FkTime,a.LoanStatus,a.ApplyMoney,a.ApplyTime,a.ApplyDay,a.YyFkTime,a.OrderSn,b.Statusyuqi,b.Status,b.jiekuandays,b.GuanliCost')
            ->join('xb_goods b','a.ProductID=b.ID',"LEFT")
            ->where('a.UserID',$userId)->where('a.LoanStatus','in','1,2,5,6,7')->find();
            if($applyData) //有正在进行中的订单
            {
                $after=(int)$applyData['jiekuandays']-1;
                $after =$after*24*60*60;
                $after=strtotime($applyData['YyFkTime'])+$after;
                $applyData['afterXuDate']=date('Y-m-d',$after);
                if($applyData['LoanStatus']=='5'){//如果被拒 显示倒计时
                    $ForbidDay =((int)$applyData['ForbidDay'])*86400;
                    $dateY = date('Y',strtotime($applyData['FkTime'])+$ForbidDay);
                    $dateM = (int)date('m',strtotime($applyData['FkTime'])+$ForbidDay)-1;
                    $dateD = (int)date('d',strtotime($applyData['FkTime'])+$ForbidDay);
                }
                if($applyData['LoanStatus']=='2'){//如果已放款 显示距离还款日天数
                    $timeTemp = strtotime($applyData['YyFkTime'])-time();
                    $endDay=ceil($timeTemp/86400);
                    $YyFkTime= strtotime($applyData['YyFkTime']);
                    $today= strtotime(date('Y-m-d 00:00:00'));
                    $yqdate = (int)ceil(($YyFkTime-$today)/86400);
                    if($yqdate<0) //逾期
                    {
                        $yuDay=abs($yqdate);
                        $applyData['LoanStatus'] =9;
                        if($applyData['Statusyuqi'] ==1)
                        {
                            $isShow=1;
                        }else{
                            $isShow=0;
                        }
                    }else{ //未逾期
                        if($applyData['Status'] ==1)
                        {
                            $isShow=1;
                        }else{
                            $isShow=0;
                        }
                    }
                }
            }else{
                $applyData =null;
            }
            $bankData = Db::table('xb_renzen_bank')->field('BankName,BankNo,YMobile')->where('UserID',$userId)->find();
            if(!$bankData)
            {
                $bankData =null;
            }
        }
        // var_dump($isShow);
        $this->assign(
            ['authen'=>$count,'user'=>$user,'goodsLits'=>$goodsLits,'default'=>$default,'applyData'=>$applyData,'bankData'=>$bankData,'Y'=>$dateY,'M'=>$dateM,'D'=>$dateD,'endDay'=>$endDay,'yuDay'=>$yuDay,'isShow'=>$isShow]);
        return $this->fetch();
    }

    /*
    *认证页
    */
    public function authen(){
        $this->base();
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $data =input('get.');
        if(!empty($data)){
            $pub_key = "f7b2fac9-0fb9-43f6-9406-c7c3bd6dfee5";
            $Security_key="9291591d-e051-4c46-800f-8e0753ddaffb";
            $sign_time=date('YmdHis');
            $partner_order_id = $data['partner_order_id'];
            $signStr = "pub_key=".$pub_key."|partner_order_id=".$partner_order_id."|sign_time=".$sign_time."|security_key=".$Security_key;
            $sign =md5($signStr);
            $url = "https://idsafe-auth.udcredit.com/front/4.3/api/order_query/pub_key/{$pub_key}";  
            $res =httpJson($url,array("header"=>array('sign'=>$sign,'partner_order_id'=>$partner_order_id,"sign_time"=>$sign_time)),true);
            $data = json_encode($res,JSON_UNESCAPED_UNICODE);
             $Da =json_decode($data,1);
            if($res['result']['success']=='true'){
                $update['isID'] =1;
                $data_['UserID'] = $user['ID'];
                $data_['Yddatas'] =$data;
                $data_['IsDel']=0;
                $data_['Status']=1;
                $data_['RenzTime']=date('Y-m-d H:i:s');
                $img['CardFace']=$res['data']['idcard_front_photo'];
                $img['CardSide']=$res['data']['idcard_back_photo'];
                $img['Cardschi']=$res['data']['living_photo'];
		        $imgName = $userId.'.png';
                foreach($img as $k=>$val){
                    $ret = file_put_contents('./youdun/img/'.$k.$imgName, base64_decode($val));
                }
                $data_['CardFace']='/youdun/img/CardFace'.$userId.'.png';
                $data_['CardSide']='/youdun/img/CardSide'.$userId.'.png';
                $data_['Cardschi']='/youdun/img/Cardschi'.$userId.'.png';
                $data_['Name'] =$Da['data']['id_name'];
                $data_['IDCard']=$Da['data']['id_number'];
                $ret = Db::table('xb_renzen_cards')->where('UserID',$userId)->find();
                if(!$ret){
                    Db::table('xb_renzen_cards')->insert($data_);
                }
                $update['TrueName'] = $Da['data']['id_name'];
                $update['IDCard'] = $Da['data']['id_number'];
                $update['Sex'] = $Da['data']['gender'];
                Db::table('xb_mem_info')->where("UserName",$session)->update($update);

            }
        }
        $result = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank')->where('UserName',$session)->find();
                $data = Db::table('xb_renzen_parameter')->where('isShow',1)->select();

        $this->assign(['session'=>$session,'authen'=>$result,'user'=>$user,'data'=>$data]);
    	return view();
    }

    /*
    *收集银行信息页
    */
    public function bank(){
    	$this->base();
    	$session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $bankSet =['招商银行','工商银行','农业银行','中国银行','建设银行','兴业银行','中信银行','广发银行','浦发银行','平安银行','上海银行','北京银行','交通银行','光大银行','邮储银行'];
        $this->assign('user',$user);
        $this->assign('bankSet',$bankSet);
    	return view();
    }

    /*
    *收集银行信息
    */
    public function bankCollect(){
    	$this->base();
        $bankData = input('post.');
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $data['UserID'] =$userId;
        $data['BankNo'] =$bankData['bank_numer'];
        $data['YMobile'] =$bankData['mobile'];
        $data['BankName'] =$bankData['bank_name'];
        $data['IsDel'] =0;
        $data['Status'] =2;
        //银行卡认证
        $result = Db::table('xb_renzen_bank')->insert($data);
        $isID['isBank'] =1;
        if($result){
              $ret = Db::table('xb_mem_info')->where('UserName',$session)->update($isID);
              if($ret){
                    return json_encode(array('status'=>1,'msg'=>'认证成功'));
                }else{
                    return json_encode(array('status'=>0,'msg'=>'认证失败'));
                }
        }else{
            return json_encode(array('status'=>0,'msg'=>'认证失败'));
        }

    }
    /*
    *个人中心
    */
    public function my(){


    	return view();
    }

    //申请借款  <500:直接拒绝 500-600:待人工审核  >600:直接通过
    public function apply(){
        $this->base();
        $count =0;
        $applyData = input('post.');
        $session = Session::get('name');
        if($session!=null){
            $result = Db::table('xb_mem_info')->field('isID,isMobile,isSocial,isBank')->where('UserName',$session)->find();
            if($result){foreach($result as $val){ if($val==1){ $count ++; }}}
        }
        $must = Db::table('xb_renzen_parameter')->where('IsMust',1)->select();
        $must =count($must);
        if($count<$must){
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'尚未认证完整'),JSON_UNESCAPED_UNICODE);
        }  
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];  
            $result = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in',[1,2,5,6,7])->find();
            if($result){
                return json_encode(array('status'=>0,'data'=>null,'msg'=>'您有一条订单正在处理'),JSON_UNESCAPED_UNICODE);
            }

        $data['UserID'] =$userId;
        $data['OrderSn'] =date('Ymdhis').rand(1000,9999);
        $data['ApplyTime']=date('Y-m-d H:i:s');
        $data['ApplyMoney']=(int)$applyData['SalePrice'];
        $data['ApplyDay'] =(int)$applyData['jiekuandays'];
        $data['YyFkTime']=$applyData['YyFkTime'];
        $data['LoanStatus']= 7;
        $data['IsDel']=0;
        $data['ProductID']=$applyData['ID'];
        $data['Interest']=(int)$applyData['GuanliCost'];
        $data['zhanqifei'] =$applyData['zhanqifei'];
        $data['yuqililv']=$applyData['yuqulv'];
        $data['nianhualilv']=$applyData['nianhualilv'];
        $data['AdoptMoney']=(int)$applyData['daozhang'];

        // //机审
        // $mScore = 500;
        // $rScore =600;
        // //风控分数
        // $Fkscore=400;
        // if($Fkscore<$mScore){
        //     $data['LoanStatus']= 5;//refuse 
        // }elseif ($Fkscore>$rScore){
        //     $data['LoanStatus']= 1;//pass 
        // }else{
        //     $data['LoanStatus']= 7;//wait be checked
        // }
        $result = Db::table('xb_loans_applylist')->insert($data);
        if($result){
        	$ret =DB::table('xb_mem_info')->where('ID',$userId)->update(array('IsApply'=>0,'Status'=>2));
        	if($ret){
            	return json_encode(array('status'=>1,'msg'=>'申请成功'),JSON_UNESCAPED_UNICODE);
        	}else{
            	return json_encode(array('status'=>1,'msg'=>'老客借款'),JSON_UNESCAPED_UNICODE);
        	}
        }else{
        	return json_encode(array('status'=>0,'msg'=>'申请失败'),JSON_UNESCAPED_UNICODE);
        }
    }

    //确认借款页
    public function applyIndeed(){
        $this->base();
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
    	$data = input('get.');
    	$data =json_decode($data['param'],true);
    	$data['TrueName']=$user['TrueName'];
    	$data['YyFkTime'] =date('Y-m-d',strtotime('+'.($data['jiekuandays']-1).'days'));
    	// var_dump($data);
    	$this->assign('data',$data);
    	return view();
    }

    //获取产品信息
    public function applyProduct(){
    	$data =input('post.');
    	$ApplyMoney=(int)trim($data['ApplyMoney'],'￥');
    	$result = Db::table('xb_goods')->where('SalePrice',$ApplyMoney)->find();
		if($result){
            return json_encode(array('status'=>1,'data'=>$result,'msg'=>'获取成功'));
		}else{
            return json_encode(array('status'=>0,'data'=>null,'msg'=>'获取失败'));
		} 		   	
    }

    /*
    *借款记录 同一时间内，一个用户只有一个订单在 申请中 审核中 放款中
    */
    public function applyRecord(){
        $this->base();
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $result = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in','1,2,6,7')->select();//进行中的
        if(count($result)>1) exit('订单异常');
        if($result)
        {
            $YyFkTime = strtotime($result[0]['YyFkTime']);
            $today = strtotime(date('Y-m-d 00:00:00'));
            $day = (int)ceil(($YyFkTime-$today)/86400);
            if($day<0)
            {
                $result[0]['Yqdays']=abs($day);
                $result[0]['YqMoney']=$result[0]['ApplyMoney']*$result[0]['Yqdays']*$result[0]['yuqililv'];
            }
            $this->assign('data',$result);
        }else{
            $this->assign('data',null);
        }
        $results = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('LoanStatus','in','3,4,5')->select();//已完成的
        if($results){
            foreach($results as &$val){
                if($val['LoanStatus']=='3'){
                    $hkRes = Db::table('xb_loans_hklist')->where('ApplyID',$val['ID'])->where('UserID',$userId)->find();
                    if($hkRes){
                        $val['hkTime']=date('Y-m-d',strtotime($hkRes['HkTime']));
                    }else{
                       exit('还款异常！');  
                    }
                }else{
                    $val['hkTime']=date('Y-m-d',strtotime($val['ApplyTime']));
                }
            }
        }else{
           $results=null; 
        }
        $this->assign('datas',$results);
        $this->assign('s',array('1'=>'放款中','2'=>'已放款','3'=>'已完成','4'=>'已取消','5'=>'已拒绝','6'=>'等待银行打款','7'=>'待人工审核'));
    	return view();
    }
   /*
    *借款详情
    */
    public function applyDetail(){
    	$this->base();
        $id =input('get.id');
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $ret = Db::table('xb_loans_applylist')->where('UserID',$userId)->where('ID',$id)->find();
        if($ret){

            $YyFkTime = strtotime($ret['YyFkTime']);
            $today = strtotime(date('Y-m-d 00:00:00'));
            $day = (int)ceil(($YyFkTime-$today)/86400);
            $ret['shouldPay']=$ret['ApplyMoney'];
            $hkRes = Db::table('xb_loans_hklist')->where('ApplyID',$id)->where('UserID',$userId)->find();
            if($hkRes)
            {
                $ret['Hktime'] =$hkRes['HkTime'];
                $ret['sjPay'] =$hkRes['TotalMoney'];
                $tDay = strtotime($ret['Hktime']);
                $day=(int)ceil(($YyFkTime-$tDay)/86400);
            }else{
                exit('订单异常');
            }
            if($day<0)
            {//逾期
    
                $ret['Yqdays']=abs($day);
                $ret['YqMoney']=$ret['ApplyMoney']*$ret['Yqdays']*$ret['yuqililv'];
            }else{
                $ret['Yqdays']=0;
                $ret['YqMoney']=0;
                $ret['Hktime'] =date('Y-m-d',strtotime($hkRes['HkTime']));
                $ret['sjPay'] =$hkRes['TotalMoney'];                   
            }

            
        }else{
            exit('订单异常');
        }
        // var_dump($ret);
        $this->assign('data',$ret);
    	return view();
    }
   /*
    *订单详情
    */
    public function orderDetail(){
    	$this->base();

    	return view();
    }
    /**
    *账单续期
    */
    public function orderRenewal(){
    	$this->base();
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $result = Db::table('xb_loans_applylist')->where('UserID',$userId)->find();
        $bankData=Db::table('xb_renzen_bank')->where('UserID',$userId)->find();
        $this->assign(['applyData'=>$result,'user'=>$user,'bankData'=>$bankData]);
    	return view();
    }

    /**
    *登录
    */
    public function login(){
        return view();
    }

    /**
    *登录验证
    */
    public function loginCheck(){
        $post = input('post.');
        if($post['mobile']){
            $code = Db::table('xb_sms_code')->where('Name',$post['mobile'])->order('UpdateTime desc')->find();
            $nowTime = time();
            $sendTime =strtotime($code['UpdateTime']);
            if($nowTime-$sendTime<300){
                if($code['Code'] == $post['verify'] ){
                    Session::set('name',$post['mobile']);
                    $data['UserName'] = $data['Mobile'] = $post['mobile'];
                    $data['LoginTime'] =date("Y-m-d H:i:s");
                    $data['RegTime'] = date('Y-m-d H:i:s');
                    $isExist = Db::table('xb_mem_info')->where('Mobile',$post['mobile'])->find();
                    if(!$isExist){
                        $goodsRet = Db::table('xb_goods')->where('defont',1)->find();
                        $data['LimitBalcance']=$goodsRet['SalePrice'];
                         $result = Db::table('xb_mem_info')->insert($data);
                        if($result){
                            return json_encode(array('status'=>1,'msg'=>'登录成功'));
                        }else{
                            return json_encode(array('status'=>0,'msg'=>'网络异常1'));
                        }
                    }else{
                        $update['RegTime'] =date('Y-m-d H:i:s');
                        Db::table('xb_mem_info')->where("Mobile",$post['mobile'])->update($update);
                        return json_encode(array('status'=>1,'msg'=>'近期已登录'));
                    }
                }else{
                    return json_encode(array('status'=>0,'msg'=>'验证码错误'));
                }
            }else{
                return json_encode(array('status'=>0,'msg'=>'验证码已失效'));
            }
        }else{
            return json_encode(array('status'=>0,'msg'=>'网络异常'));
        }
    }

    /*
    *发送验证码
    */
    public function sendVerify(){
        $datas = input('post.');
        $mobile = $datas['mobile'];
        if(!$mobile){
            return json_encode(array('status'=>1,'msg'=>'手机号不能为空'));
        }
        // $result =  sendMsg($mobile);
        $result= array(1,123456);
        $data['Name'] = $mobile;
		if($result[0] ==1){
			$data['Code'] = $result[1];
			$data['UpdateTime'] = date("Y_m-d H:i:s");
			$result = Db::table('xb_sms_code')->insert($data);
			if($result){
				return json_encode(array('status'=>1,'msg'=>'验证码发送成功'));
			}else{
				return json_encode(array('status'=>0,'msg'=>'验证码发送失败.'));
			}
		}else{
    		return json_encode(array('status'=>0,'msg'=>'验证码发送失败'));
        }
    }

    /*
    *   社交认证
    */
   public function social(){
        return  $this->fetch();
    }

   public function socialCollect(){
        $data = input('post.');
        $session = Session::get('name');
        $user = Db::table('xb_mem_info')->where('UserName',$session)->find();
        $userId = $user['ID'];
        $data['UserID'] =$userId;
        // $isExist =Db::table('xb_renzen_social')->where('UserID',$userId)->find();
        // if(!$isExist){
            $data['RenzTime']=date("Y-m-d H:i:s");
            $data['UpdateTime']=date("Y-m-d H:i:s");
            $data['IsDel'] =0;
            $data['Status'] =1;
            $result = Db::table('xb_renzen_social')->insert($data);
            $isID['isSocial'] =1;
            $ret = Db::table('xb_mem_info')->where('UserName',$session)->update($isID);
            if($result && $ret){
                return json_encode(array('status'=>1,'msg'=>'认证成功'));
            }else{
                return json_encode(array('status'=>0,'msg'=>'认证失败或已认证'));
            }
        // }
    }



















 










































}
